package pfx;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.PasswordAuthentication;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.util.Enumeration;

import org.apache.commons.io.FileUtils;

public class Get_private_from_pfx {

	/**
	 * 1. 读入 pfx 文件
	 * 2. 转换为 字节数组
	 * 3. 载入 keystore
	 * 4. 枚举得到  alias .
	 * 5. 获取 私钥
	 * 
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
	
		String pfx_path = "C:\\Users\\Administrator\\Desktop\\ttt\\bankside092502.pfx";
		String password = "123456";
		
		PrivateKey privateKey = get_privateKey(pfx_path, password);

	}

	public static PrivateKey get_privateKey(String pfx_path,String password) throws Exception{
		
		PrivateKey privateKey = null;
		// 读取文件
		File file = new File(pfx_path);
		byte[] pfx_byte = FileUtils.readFileToByteArray(file);
		
		// 读入 keystore
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		keyStore.load(new ByteArrayInputStream(pfx_byte), password.toCharArray());
		
		// 获取证书条目
		Enumeration<String> enums = keyStore.aliases();
		String alia = "";
		
		while(enums.hasMoreElements()){
			alia = enums.nextElement();
			if(keyStore.isKeyEntry(alia)){
				privateKey = (PrivateKey) keyStore.getKey(alia, password.toCharArray());
			}	
		}
		return privateKey;
	}
	
	
	
	
}









